package com.demo2.contrller;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

public class TestVelocity extends HttpServlet {

    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //载入配置文件
        Properties p=new Properties();
        p.setProperty("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(p);

        //取得VelocityContext作用域
        VelocityContext context = new VelocityContext();
        //将list放入context作用域
        context.put("list", getNames());
        context.put("uname", "Vic");

        Template template = null;
        String templateFile = "templates/example.vm";
        try {
            //载入模板文件
            template = Velocity.getTemplate(templateFile);
        } catch (ResourceNotFoundException rnfe) {
            System.out.println("Example : error : cannot find template "+ templateFile);
        } catch (ParseErrorException pee) {
            System.out.println("Example : Syntax error in template "+ templateFile + ":" + pee);
        }
        BufferedWriter writer = new BufferedWriter(response.getWriter());
        if (template != null)
            template.merge(context, writer);
        writer.flush();
        writer.close();
    }
    private ArrayList getNames() {
        ArrayList list = new ArrayList();
        list.add("ArrayList element 1");
        list.add("ArrayList element 2");
        list.add("ArrayList element 3");
        list.add("ArrayList element 4");
        return list;
    }
    public void init() throws ServletException {
        super.init();
    }
}
